<template>
  <div class="read_container">
    <div class="catalog" :style="catalogStyle" @click="readbook">
      <div class="cataItem ellipsis" ref="chapter" v-for="chapter,i in chapters" :key="i" :data-source="chapter.chapterUrl" :class="{active:chapter.chapterUrl == source}">
        {{chapter.chapterName}}
      </div>
    </div>
    <router-view class="viewContent"/>
  </div>
</template>

<script>
import { mapState } from 'vuex'
export default {
  name: 'Read',
  data (){
    return {
      catalogTranslateX: '-101%'
    }
  },
  async mounted (){
    let source = this.source
    const index = source.lastIndexOf('/')
    if (source.indexOf('.html') > -1){
      source = source.slice(0, index)
    }
    // 获取章节列表
    await this.$store.dispatch('chapters', source)
    this.activeChapterScrollTop(this.source)
  },
  methods: {
    readbook (e){
      const source = e.target.dataset.source
      if (source === this.source) return ''
      this.$router.push({ name: 'ReadBook', query: { source } })
      this.$store.dispatch('content', { source, replace:true })
      this.$store.commit('SHOWCATALOG', '-101%')
    },
    // 修改阅读章节的scrollTop
    activeChapterScrollTop (val, line = 4){
      this.$nextTick(() => {
        for (let i = 0; i < this.$refs.chapter.length; i++){
          const chapter = this.$refs.chapter[i]
          if (chapter.dataset.source === val){
            const height = chapter.offsetHeight
            const top = chapter.offsetTop
            // 将当前章节名称放在第四个位置显示
            if (top > height * line) {
              chapter.parentNode.scrollTop = top - height * 4
            }
            break
          }
        }
      })
    }
  },
  computed: {
    ...mapState({
      catalogStyle: state => {
        const num = state.novel.showCatalog
        return {
          transform: `translateX(${num})`
        }
      },
      source (){
        return this.$route.query.source
      },
      chapters: state => state.novel.chapters
    })
  },
  watch: {
    source (val){
      this.activeChapterScrollTop(val)
    }
  }
}
</script>

<style lang="less" scoped>
.read_container {
  position: relative;
  .catalog{
    position: fixed;
    height: 100vh;
    z-index: 20;
    overflow-y:scroll ;
    width: 70%;
    top: 0;
    bottom: 0;
    left: 0;
    background-color: var(--main-bg);
    z-index: 20;
    transition: all .25s ease-in;
    transform: translateX(-101%);
    .cataItem{
      line-height: 2;
      padding: .3em 1em;
    }
    .active{
      color: rebeccapurple;
    }
  }
  .viewContent{

  }
}
</style>
